package server;

import com.esotericsoftware.minlog.Log;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JEditorPane;

public class ServerLog {
    
    private JEditorPane editorPane;
    private List<String> logList;
    private DateFormat dateFormat;
    
    public ServerLog(JEditorPane editorPane) {
        this.editorPane = editorPane;
        this.editorPane.setContentType("text/html");
        this.editorPane.setEditable(false);
        
        logList = new ArrayList<>();
        dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    }
    
    public void write(int type, String text) {
        text = text.replace("\n", "<br>");
        
        switch (type) {
            case Log.LEVEL_INFO:
                logList.add(String.format("<span style=\"font-family: Arial, sans-serif; font-size: 10px;\"><span style=\"color: gray;\">[%s]</span> %s</span>", dateFormat.format(new Date()), text));
                break;
            case Log.LEVEL_ERROR:
                logList.add(String.format("<span style=\"font-family: Arial, sans-serif; font-size: 10px;\"><span style=\"color: gray;\">[%s]</span> <span style=\"color: red;\">%s</span></span>", dateFormat.format(new Date()), text));
                break;
            default:
                logList.add(String.format("<span style=\"font-family: Arial, sans-serif; font-size: 10px;\"><span style=\"color: gray;\">[%s]</span> %s</span>", dateFormat.format(new Date()), text));
                break;
        }
        
        update();
    }
    
    public void write(int type, String text, Exception ex) {
        text = String.format("%s\n%s", text, ex.getLocalizedMessage());
        
        write(type, text);
    }
    
    public void clear() {
        logList.clear();
        
        update();
    }
    
    private void update() {
        StringBuilder sb = new StringBuilder("<html><body>");
        
        for (String log : logList) {
            sb.append(log).append("<br>");
        }
        
        sb.append("</body></html>");
        
        editorPane.setText(sb.toString());
        editorPane.setCaretPosition(editorPane.getDocument().getLength());
    }
    
}
